import { defineStore } from "pinia";
import userApi, { type FormData } from '@/api/login/login'
import userInfoApi from "@/api/centerMock/index";

export const useUserInfoStore = defineStore({
    id: "app",
    state: () => ({
        // token: 'a0b5ff67-6fe1-4711-a805-3d2b7604f0c2',
        userInfo: {
            account: "",
            avatar: "",
            avocation: [],
            level: 0,
            moreBackup: {},
            gender: "",
            birthday: "",
            city: "",
            skillevel: "",
        },
        // token: ''
        token: localStorage.getItem('TOKEN')
    }),

    actions: {
        // 登录
        async login(reqLogin: FormData) {
            try {
                let result = await userApi.reqLogin(reqLogin)
                // pinia 存 token
                this.token = 'a0b5ff67-6fe1-4711-a805-3d2b7604f0c2'
                // localStorage 存 token
                localStorage.setItem('TOKEN', this.token)
                console.log(result)
            } catch (error) {
                console.error('登陆失败')
                return Promise.reject(error)
            }
        },
        // 退出登录
        async loginOut() {
            try {
                await userApi.reqLogout()
                // 清空store中token
                this.token = ''
                // 清空 localStorage 中token
                localStorage.removeItem('TOKEN')
                // console.log('pinia退出登录')
            } catch (error) {
                console.error('退出登录失败')
                return Promise.reject(error)
            }
        },
        // 注册
        async register(reqLogin: any) {
            try {
                await userApi.reqRegister(reqLogin)
            } catch (error) {
                console.error('注册失败')
                return Promise.reject(error)
            }
        },
        // 获取验证码
        // async getCode(phone: any) {
        //     try {
        //         let result = await userApi.reqCode(phone)
        //         console.log('验证码', result.data)
        //         return Promise.reject(result.data)

        //     } catch (error) {
        //         console.error('获取验证码失败')
        //         return Promise.reject(error)
        //     }
        // }

        async getUserInfo() {
            try {
                let res = await userInfoApi.reqUserInfo();
                // console.log(res);
                let { account, avatar, avocation, level, moreBackup } = res;
                this.userInfo = {
                    account,
                    avatar,
                    avocation,
                    level,
                    moreBackup,
                    gender: "男",
                    birthday: "",
                    city: "",
                    skillevel: "",
                };
            } catch (error) {
                return Promise.reject(error);
            }
        },
    },
    getters: {},
});


